package cn.lili.modules.system.serviceimpl;

import cn.hutool.core.util.ObjectUtil;
import cn.lili.cache.Cache;
import cn.lili.common.enums.DictCodeEnum;
import cn.lili.common.utils.*;
import cn.lili.common.vo.PageVO;
import cn.lili.modules.goods.entity.dto.GoodsAndStores;
import cn.lili.modules.goods.entity.dto.GoodsSearchParams;
import cn.lili.modules.goods.entity.vos.GoodsSkuVO;
import cn.lili.modules.goods.entity.vos.GoodsVO;
import cn.lili.modules.goods.service.GoodsService;
import cn.lili.modules.goods.service.GoodsSkuService;
import cn.lili.modules.store.entity.dos.Store;
import cn.lili.modules.store.entity.enums.StoreStatusEnum;
import cn.lili.modules.store.entity.vos.StoreSearchParams;
import cn.lili.modules.store.entity.vos.StoreVO;
import cn.lili.modules.system.mapper.RegionMapper;
import cn.lili.modules.system.service.RegionService;
import cn.lili.modules.system.entity.dos.Region;
import cn.lili.modules.system.entity.vo.RegionVO;
import cn.lili.modules.wallet.entity.dto.CommissionDistributionSale;
import cn.lili.mybatis.util.PageUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * 行政地区业务层实现
 *
 * @author Chopper
 * @since 2020/12/2 11:11
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class RegionServiceImpl extends ServiceImpl<RegionMapper, Region> implements RegionService {

	/**
	 * 同步请求地址
	 */
	private String syncUrl = "https://restapi.amap.com/v3/config/district?subdistrict=4&key=e456d77800e2084a326f7b777278f89d";

	@Autowired
	private Cache cache;
	/**
	 * 商品
	 */
	@Autowired
	private GoodsService goodsService;

	@Autowired
	private GoodsSkuService goodsSkuService;

	@Override
	public void synchronizationData(String url) {
		try {

			// 清空数据
			QueryWrapper<Region> queryWrapper = new QueryWrapper();
			queryWrapper.ne("id", "-1");
			this.remove(queryWrapper);

			// 读取数据
			String jsonString = HttpClientUtils.doGet(StringUtils.isEmpty(url) ? syncUrl : url, null);

			// 构造存储数据库的对象集合
			List<Region> regions = this.initData(jsonString);
			for (int i = 0; i < (regions.size() / 100 + (regions.size() % 100 == 0 ? 0 : 1)); i++) {
				int endPoint = Math.min((100 + (i * 100)), regions.size());
				this.saveBatch(regions.subList(i * 100, endPoint));
			}
			// 删除缓存
			cache.vagueDel("{regions}");
		} catch (Exception e) {
			log.error("同步行政数据错误", e);
		}
	}

	@Override
	public List<Region> getItem(String id) {
		LambdaQueryWrapper<Region> lambdaQueryWrapper = new LambdaQueryWrapper<>();
		lambdaQueryWrapper.eq(Region::getParentId, id);
		List<Region> regions = this.list(lambdaQueryWrapper);
		regions.sort(new Comparator<Region>() {
			@Override
			public int compare(Region o1, Region o2) {
				return o1.getOrderNum().compareTo(o2.getOrderNum());
			}
		});
		return regions;
	}

	/**
	 * g根据id/或者Code获取区域adCode
	 *
	 * @param id
	 *            地区ID
	 * @return
	 */
	@Override
	public List getItemAdCod(String id) {
		List list = new ArrayList();
		if (id.length() == 6) {
			for (int i = 0; i < id.length(); i += 2) {
				String addCode_2 = StringUtils.sub(id, i, i + 2);
				if (addCode_2.equals("00")) {
					id = StringUtils.replace(id, i, i + 2, '_');
				}
			}
			List<Map<String, Object>> itemAdCod = baseMapper.getItemAdCodByAdcode(id);
			for (Map<String, Object> map : itemAdCod) {
				list.add(map.get("adCode"));
			}
		} else {
			if (StringUtils.isNotEmpty(id)) {
				String[] split = id.split(",");
				List<Map<String, Object>> itemAdCod = baseMapper.getItemAdCod(split[split.length - 1]);
				for (Map<String, Object> map : itemAdCod) {
					list.add(map.get("adCode"));
				}
			}
		}
		return list;
	}

	@Override
	public Region getItemAdCodAll(String adCode) {
		return baseMapper.getItemAdCodAll(adCode);
	}

	/**
	 * g根据id/或者Code获取区域adCode
	 *
	 * @param id
	 *            地区ID
	 * @return
	 */
	@Override
	public List getPartnerAdCode(String adcode, String type) {
		String id = adcode;
		List list = new ArrayList();
		if (id.length() == 6) {
			for (int i = 0; i < id.length(); i += 2) {
				String addCode_2 = StringUtils.sub(id, i, i + 2);
				if (addCode_2.equals("00")) {
					id = StringUtils.replace(id, i, i + 2, '_');
				}
			}
			List<Map<String, Object>> itemAdCod = baseMapper.getPartnerAdCodeByAdcode(id, type, adcode);
			for (Map<String, Object> map : itemAdCod) {
				list.add(map.get("adCode"));
			}
		} else {
			if (StringUtils.isNotEmpty(id)) {
				String[] split = id.split(",");
				List<Map<String, Object>> itemAdCod = baseMapper.getItemAdCod(split[split.length - 1]);
				for (Map<String, Object> map : itemAdCod) {
					list.add(map.get("adCode"));
				}
			}
		}
		return list;
	}

	/**
	 * 根据ad_code去找上级省市区
	 */
	@Override
	public String getItemAdCodOrName(String adCode) {
		String Region = "";
		if (StringUtils.isNotEmpty(adCode)) {
			Region itemAdCodAll = baseMapper.getItemAdCodAll(adCode);
			String path = itemAdCodAll != null ? itemAdCodAll.getPath() : "";
			if (StringUtils.isNotEmpty(path)) {
				// String[] split = path.substring(3, path.length()).split(",");

				String[] split = path.split(",");
				for (int a = 0; a < split.length && a <= 3; a++) {
					// for (int a = 0; a < split.length; a++) {
					Region byId = this.getById(split[a]);
					if (byId != null)
						Region += byId.getName();
				}
				Region = Region + itemAdCodAll.getName();
			}
		}
		return Region;
	}

	@Override
	public Map<String, Object> getRegion(String addressCode, String townName) {
		// 获取地址信息
		Region region = this.baseMapper
				.selectOne(new QueryWrapper<Region>().eq("ad_code", addressCode).eq("name", townName));
		if (region != null) {
			// 获取它的层级关系
			String path = region.getPath();
			String[] result = path.split(",");
			// 因为有无用数据 所以先删除前两个
			result = ArrayUtils.remove(result, 0);
			result = ArrayUtils.remove(result, 0);
			// 地址id
			String regionIds = "";
			// 地址名称
			String regionNames = "";
			// 循环构建新的数据
			for (String regionId : result) {
				Region reg = this.baseMapper.selectById(regionId);
				if (reg != null) {
					regionIds += regionId + ",";
					regionNames += reg.getName() + ",";
				}
			}
			regionIds += region.getId();
			regionNames += region.getName();
			// 构建返回数据
			Map<String, Object> obj = new HashMap<>(2);
			obj.put("id", regionIds);
			obj.put("name", regionNames);
			return obj;
		}
		return null;
	}

	@Override
	public List<RegionVO> getAllCity() {
		LambdaQueryWrapper<Region> lambdaQueryWrapper = new LambdaQueryWrapper<>();
		// 查询所有省市
		lambdaQueryWrapper.in(Region::getLevel, "city", "province");
		return regionTree(this.list(lambdaQueryWrapper));
	}

	private List<RegionVO> regionTree(List<Region> regions) {
		List<RegionVO> regionVOS = new ArrayList<>();
		regions.stream().filter(region -> ("province").equals(region.getLevel())).forEach(item -> {
			regionVOS.add(new RegionVO(item));
		});
		regions.stream().filter(region -> ("city").equals(region.getLevel())).forEach(item -> {
			for (RegionVO region : regionVOS) {
				if (region.getId().equals(item.getParentId())) {
					region.getChildren().add(new RegionVO(item));
				}
			}
		});
		return regionVOS;
	}

	/**
	 * 构造数据模型
	 *
	 * @param jsonString
	 * @throws Exception
	 */
	private List<Region> initData(String jsonString) {

		// 最终数据承载对象
		List<Region> regions = new ArrayList<>();
		JSONObject jsonObject = JSONObject.parseObject(jsonString);
		// 获取到国家及下面所有的信息 开始循环插入，这里可以写成递归调用，但是不如这样方便查看、理解
		JSONArray countryAll = jsonObject.getJSONArray("districts");
		for (int i = 0; i < countryAll.size(); i++) {
			JSONObject contry = countryAll.getJSONObject(i);
			String id1 = "0";
			JSONArray provinceAll = contry.getJSONArray("districts");
			for (int j = 0; j < provinceAll.size(); j++) {
				JSONObject province = provinceAll.getJSONObject(j);
				String citycode1 = province.getString("citycode");
				String adcode1 = province.getString("adcode");
				String name1 = province.getString("name");
				String center1 = province.getString("center");
				String level1 = province.getString("level");
				// 插入省
				String id2 = insert(regions, id1, citycode1, adcode1, name1, center1, level1, j, id1);
				JSONArray cityAll = province.getJSONArray("districts");

				for (int z = 0; z < cityAll.size(); z++) {
					JSONObject city = cityAll.getJSONObject(z);
					String citycode2 = city.getString("citycode");
					String adcode2 = city.getString("adcode");
					String name2 = city.getString("name");
					String center2 = city.getString("center");
					String level2 = city.getString("level");
					// 插入市
					String id3 = insert(regions, id2, citycode2, adcode2, name2, center2, level2, z, id1, id2);
					JSONArray districtAll = city.getJSONArray("districts");
					for (int w = 0; w < districtAll.size(); w++) {
						JSONObject district = districtAll.getJSONObject(w);
						String citycode3 = district.getString("citycode");
						String adcode3 = district.getString("adcode");
						String name3 = district.getString("name");
						String center3 = district.getString("center");
						String level3 = district.getString("level");
						// 插入区县
						String id4 = insert(regions, id3, citycode3, adcode3, name3, center3, level3, w, id1, id2, id3);
						// 有需要可以继续向下遍历
						JSONArray streetAll = district.getJSONArray("districts");
						for (int r = 0; r < streetAll.size(); r++) {
							JSONObject street = streetAll.getJSONObject(r);
							String citycode4 = street.getString("citycode");
							String adcode4 = street.getString("adcode");
							String name4 = street.getString("name");
							String center4 = street.getString("center");
							String level4 = street.getString("level");
							// 插入区县
							insert(regions, id4, citycode4, adcode4, name4, center4, level4, r, id1, id2, id3, id4);

						}

					}

				}
			}
		}
		return regions;
	}

	/**
	 * 公共的插入方法
	 *
	 * @param parentId
	 *            父id
	 * @param cityCode
	 *            城市编码
	 * @param adCode
	 *            区域编码 街道没有独有的adcode，均继承父类（区县）的adcode
	 * @param name
	 *            城市名称 （行政区名称）
	 * @param center
	 *            地理坐标
	 * @param level
	 *            country:国家 province:省份（直辖市会在province和city显示）
	 *            city:市（直辖市会在province和city显示） district:区县 street:街道
	 * @param ids
	 *            地区id集合
	 * @return
	 */
	public String insert(List<Region> regions, String parentId, String cityCode, String adCode, String name,
			String center, String level, Integer order, String... ids) {
		// \"citycode\": [],\n" +
		// " \"adcode\": \"100000\",\n" +
		// " \"name\": \"中华人民共和国\",\n" +
		// " \"center\": \"116.3683244,39.915085\",\n" +
		// " \"level\": \"country\",\n" +
		Region record = new Region();
		if (!("[]").equals(adCode)) {
			record.setAdCode(adCode);
		}
		if (!("[]").equals(cityCode)) {
			record.setCityCode(cityCode);
		}
		record.setCenter(center);
		record.setLevel(level);
		record.setName(name);
		record.setParentId(parentId);
		record.setOrderNum(order);
		record.setId(String.valueOf(SnowFlake.getId()));
		StringBuffer megName = new StringBuffer(",");
		for (int i = 0; i < ids.length; i++) {
			megName = megName.append(ids[i]);
			if (i < ids.length - 1) {
				megName.append(",");
			}
		}
		record.setPath(megName.toString());
		regions.add(record);
		return record.getId();
	}

	/**
	 * 根据省市区搜素商品
	 *
	 * @param region
	 *            地区接口
	 * @return 会员地址分页列表
	 */
	public IPage<GoodsVO> getRegionCo(PageVO page, Region region) {
		String adCode = region.getChooseCode();
		System.out.println(adCode + "位置================================================");
		if (StringUtils.isEmpty(adCode) || "undefined".equals(adCode) || "".equals(adCode) || "0".equals(adCode)) {
			adCode = "110101"; // 沒有获取到定位则默认到北京东城区
		}
		Region regionId = baseMapper.getAdRegionId(adCode);
		String id = regionId.getId(); // 区域id
		// 根据区域id查询店铺和店铺的商品
		QueryWrapper<GoodsSearchParams> queryWrapper1 = Wrappers.query();
		GoodsSearchParams goodsSearchParams = new GoodsSearchParams();
		goodsSearchParams.setStoreAddressIdPath(id);
		goodsSearchParams.setPageNumber(page.getPageNumber());
		goodsSearchParams.setPageSize(page.getPageSize());
		queryWrapper1.like("a.store_address_id_path", goodsSearchParams.getStoreAddressIdPath());
		queryWrapper1.eq("a.store_disable", "OPEN"); // 店铺开启状态
		queryWrapper1.eq("g.market_enable", "UPPER"); // 商品上架状态
		IPage<GoodsVO> goodsVOIPage = baseMapper.queryByParams(PageUtil.initPage(goodsSearchParams), queryWrapper1);
		return goodsVOIPage;
	}

	/**
	 * 今日爆品，默认拿到销量前五的，和九个后面的
	 *
	 * @param region
	 *            地区接口
	 */
	public Map getCommodity(Region region) {
		// 默认销量前五的，可调节，现在是固定先写死，等需求确定好了就可以在这查询字典表进行配置
		int size = 5;
		int sunm = size + 9;
		// 城市編碼
		String adCode2 = region.getChooseCode();
		List<GoodsVO> commodity11 = new ArrayList<>();
		if (StringUtils.isNotEmpty(adCode2) && !"undefined".equals(adCode2) && !"0".equals(adCode2)) {
			Region regionId = baseMapper.getAdRegionId(adCode2);
			String id = regionId.getId(); // 区域id
			// 根据区域id查询店铺和店铺的商品
			List<GoodsVO> commodity = baseMapper.getCommodity(id, sunm);
			if (commodity.size() == sunm) {
				commodity11 = commodity;
			} else {
				// 解析adCod逻辑,市级别
				String adCode1 = adCode2.substring(0, adCode2.length() - 2) + "00";
				// 当前区域下没有热销商品则统计市 级别 以此类推
				Region regionId1 = baseMapper.getAdRegionId(adCode1);
				String id1 = regionId1.getId(); // 市级别
				List<GoodsVO> commodity1 = baseMapper.getCommodity(id1, sunm);
				if (commodity1.size() == sunm) {
					commodity11 = commodity1;
				} else {
					// 解析adCod逻辑,省级别
					String adCode3 = adCode2.substring(0, adCode2.length() - 4) + "0000";
					// 当前区域下没有热销商品则统计市 级别 以此类推
					Region regionId3 = baseMapper.getAdRegionId(adCode3); // 省级别
					String id2 = regionId3.getId();
					List<GoodsVO> commodity2 = baseMapper.getCommodity(id2, sunm);
					if (commodity2.size() == sunm) {
						commodity11 = commodity2;
					}
				}
			}
		}
		commodity11 = baseMapper.getCommodityQg(sunm);// 最后全国
		// 先拿出来前五个为爆品商品。
		List list = new ArrayList();
		// 后九个爆款商品
		List list1 = new ArrayList();
		for (int a = 0; a < commodity11.size(); a++) {
			String id = commodity11.get(a).getId(); // 商品id
			Map<String, Object> undefined = goodsSkuService.getGoodsSkuDetail(id, "undefined");
			GoodsSkuVO data = (GoodsSkuVO) undefined.get("data");
			commodity11.get(a).setPrice(data.getMemberPrice());
			if (a < size) {
				list.add(commodity11.get(a));
			} else {
				list1.add(commodity11.get(a));
			}
		}
		Map map = new HashMap();
		map.put("baopin", list);
		map.put("jiuge", list1);
		return map;
	}

	/**
	 * 本区域前几名的店铺
	 */
	public Map getCommodityShop(Region region) {
		// 默认销量前五的好店，可调节，现在是固定先写死，等需求确定好了就可以在这查询字典表进行配置
		int size = 5;
		int sunm = size + 9;
		List<Store> commodityShopQg = new ArrayList<>();
		// 城市編碼
		String adCode = region.getChooseCode();
		if (StringUtils.isNotEmpty(adCode) && !"undefined".equals(adCode) && !"0".equals(adCode)) {
			Region regionId = baseMapper.getAdRegionId(adCode);
			String id = regionId.getId(); // 区域id
			List<Store> commodityShop = baseMapper.getCommodityShop(id, sunm);
			if (commodityShop.size() == sunm) {
				commodityShopQg = commodityShop;
			} else {
				// 解析adCod逻辑,市级别
				String adCode1 = adCode.substring(0, adCode.length() - 2) + "00";
				// 当前区域下没有热销商品则统计市 级别 以此类推
				Region regionId1 = baseMapper.getAdRegionId(adCode1);
				List<Store> commodityShop1 = baseMapper.getCommodityShop(regionId1.getId(), sunm);
				if (commodityShop1.size() == sunm) {
					commodityShopQg = commodityShop1;
				} else {
					// 解析adCod逻辑,省
					String adCode3 = adCode.substring(0, adCode.length() - 4) + "0000";
					// 当前区域下没有热销商品则统计市 级别 以此类推
					Region regionId2 = baseMapper.getAdRegionId(adCode3);
					List<Store> commodityShop2 = baseMapper.getCommodityShop(regionId2.getId(), sunm);
					if (commodityShop2.size() == sunm) {
						commodityShopQg = commodityShop2;
					}
				}
			}
		}
		// 全国
		commodityShopQg = baseMapper.getCommodityShopQg(sunm);
		// 先拿出来前五个好店
		List list = new ArrayList();
		// 后九个好店
		List list1 = new ArrayList();
		for (int a = 0; a < commodityShopQg.size(); a++) {
			if (a < size) {
				list.add(commodityShopQg.get(a));
			} else {
				list1.add(commodityShopQg.get(a));
			}
		}
		Map map = new HashMap();
		map.put("haodian", list);
		map.put("jiuge", list1);
		return map;
	}

	@Override
	public IPage<StoreVO> findByConditionPage(StoreSearchParams storeSearchParams, PageVO page) {
		storeSearchParams.setStoreDisable("OPEN"); // 店铺必须是开启的店铺
		// 1本地商圈2好店推荐;本地商圈需要查詢區域，好店推荐不需要查询区域
		IPage<StoreVO> storeList = null;
		if (null != storeSearchParams.getState() && storeSearchParams.getState() == 1) {
			if (storeSearchParams.getChooseCode() != null) {
				if (StringUtils.isNotEmpty(storeSearchParams.getType()) || storeSearchParams.getType() != null) {
					if (storeSearchParams.getType().equals("销量")) {
						storeSearchParams.setMonthSales(1);
					} else if (storeSearchParams.getType().equals("评分")) {
						storeSearchParams.setScore(1.0);
					}
				}
				Region region = baseMapper.getAdRegionId(storeSearchParams.getChooseCode());// 根据adcond查询区域id
				storeSearchParams.setRegionId(region.getId());
				String lon = null;
				String lat = null;
				if (ObjectUtil.isNotEmpty(region)) {
					String center = region.getCenter();
					String[] split = center.split(",");
					lon = split[0];
					lat = split[1];
				}
				storeList = this.baseMapper.getStoreList(PageUtil.initPage(page), storeSearchParams.queryWrapper(), lon,
						lat);
				if (storeList.getRecords().size() == 0 || storeList.getTotal() == 0) {
					// 解析adCod逻辑,市级别
					String adCode1 = storeSearchParams.getChooseCode().substring(0,
							storeSearchParams.getChooseCode().length() - 2) + "00";
					Region regionId1 = baseMapper.getAdRegionId(adCode1);// 根据adcond查询区域id
					storeSearchParams.setRegionId(regionId1.getId());
					storeList = this.baseMapper.getStoreList(PageUtil.initPage(page), storeSearchParams.queryWrapper(),
							lon, lat);
					if (storeList.getRecords().size() == 0 || storeList.getTotal() == 0) {
						// 解析adCod逻辑,省级别
						String adCode2 = adCode1.substring(0, adCode1.length() - 4) + "0000";
						Region regionId2 = baseMapper.getAdRegionId(adCode2);// 根据adcond查询区域id
						storeSearchParams.setRegionId(regionId2.getId());
						storeList = this.baseMapper.getStoreList(PageUtil.initPage(page),
								storeSearchParams.queryWrapper(), lon, lat);
						if (storeList.getRecords().size() == 0 || storeList.getTotal() == 0) {
							// 省级没有店铺，查询哈尔滨
							Region regionId3 = baseMapper.getAdRegionId("230100");// 根据adcond查询区域id
							storeSearchParams.setRegionId(regionId3.getId());
							storeList = this.baseMapper.getStoreList(PageUtil.initPage(page),
									storeSearchParams.queryWrapper(), lon, lat);
						}
					}
				}
			} else {
				// 没有区域，默认显示哈尔滨
				Region region = baseMapper.getAdRegionId("230100");// 根据adcond查询区域id
				storeSearchParams.setRegionId(region.getId());
				String lon = null;
				String lat = null;
				if (ObjectUtil.isNotEmpty(region)) {
					String center = region.getCenter();
					String[] split = center.split(",");
					lon = split[0];
					lat = split[1];
				}
				storeList = this.baseMapper.getStoreList(PageUtil.initPage(page), storeSearchParams.queryWrapper(), lon,
						lat);
			}
		}
		return storeList;
	}

	@Override
	public IPage<GoodsVO> queryByParams(GoodsSearchParams goodsSearchParams) {
		// return this.page(PageUtil.initPage(goodsSearchParams),
		// goodsSearchParams.queryWrapper());
		// 1实物商品2爆品商品;实物商品需要查询区域，爆品商品不需要
		// if (goodsSearchParams.getState() == 1) {
		// if (goodsSearchParams.getChooseCode() != null) {
		// Region regionId =
		// baseMapper.getAdRegionId(goodsSearchParams.getChooseCode());//根据adcond查询区域id
		// goodsSearchParams.setStoreAddressIdPath(regionId.getId());
		// } else {
		// goodsSearchParams.setStoreAddressIdPath("-1"); //没有商品地区
		// }
		// }
		IPage<GoodsVO> goodsVOIPage = baseMapper.queryByParamss(PageUtil.initPage(goodsSearchParams),
				goodsSearchParams.queryWrapper());
		if (null != goodsVOIPage.getRecords()) {
			for (GoodsVO goodsVO : goodsVOIPage.getRecords()) {
				// 商品sku赋值
				List<GoodsSkuVO> goodsListByGoodsId = goodsSkuService.getGoodsListByGoodsId(goodsVO.getId());
				if (goodsListByGoodsId != null && !goodsListByGoodsId.isEmpty()) {
					goodsVO.setSkuList(goodsListByGoodsId);
				}
			}
		}
		return goodsVOIPage;
	}

	@Override
	public List<Region> getItemBySetting(String id) {
		LambdaQueryWrapper<Region> lambdaQueryWrapper = new LambdaQueryWrapper<>();
		lambdaQueryWrapper.eq(Region::getParentId, id);
		List<Region> regions = this.list(lambdaQueryWrapper);
		regions.sort(new Comparator<Region>() {
			@Override
			public int compare(Region o1, Region o2) {
				return o1.getOrderNum().compareTo(o2.getOrderNum());
			}
		});
		return regions;
	}

	@Override
	public List<StoreVO> getGoodShop(StoreSearchParams storeSearchParams) {
		storeSearchParams.setStoreDisable("OPEN"); // 店铺必须是开启的店铺
		// 1本地好店
		List<StoreVO> storeList = new ArrayList<>();
		if (StringUtils.isNotEmpty(storeSearchParams.getChooseCode())) {
			String trapeze = storeSearchParams.getTrapeze();
			String lon = "";
			String lat = "";
			if (StringUtils.isNotEmpty(trapeze)) {
				String[] split = trapeze.split(",");
				lon = split[0];
				lat = split[1];
			}
			storeSearchParams.setSelfOperated(0);
			if (!storeSearchParams.getChooseCode().equals("000000")) {
				Integer limit = Integer.parseInt(SysDictUtils.getValueString(DictCodeEnum.GOODS_SHOP_LIMIT.dictCode()));
				limit = limit != null && limit > 0 ? limit : null;
				String chooseCode = storeSearchParams.getChooseCode();
				storeSearchParams.setLimit(limit);
				StoreSearchParams searchParams = storeSearchParams;
				storeSearchParams.setOrderByCommendRanking(true);
				List<StoreVO> storeList1 = getGoodShop(storeSearchParams, chooseCode, null, lon, lat);
				storeList.addAll(storeList1);
				if (limit != null && storeList.size() < limit) {
					// 本区域内推荐店铺不够十个，查询本区域未推荐店铺
					searchParams.setRecommend(false);
					searchParams.setLimit(limit - storeList.size());
					searchParams.setDistance1(1);
					List<StoreVO> storeList5 = getGoodShop(storeSearchParams, chooseCode, null, lon, lat);
					storeList.addAll(storeList5);
					if (storeList.size() < limit) {
						// 解析adCod逻辑,市级别
						String chooseCode1 = storeSearchParams.getChooseCode().substring(0,
								storeSearchParams.getChooseCode().length() - 2) + "00";
						if (!chooseCode.equals(chooseCode1)) {
							storeSearchParams.setLimit(limit - storeList.size());
							List<StoreVO> storeList2 = getGoodShop(storeSearchParams, chooseCode1, chooseCode, lon,
									lat);
							storeList.addAll(storeList2);
						}
						if (storeList.size() < limit) {
							// 解析adCod逻辑,省级别
							String chooseCode2 = chooseCode1.substring(0, chooseCode1.length() - 4) + "0000";
							if (!chooseCode2.equals(chooseCode1)) {
								storeSearchParams.setLimit(limit - storeList.size());
								List<StoreVO> storeList3 = getGoodShop(storeSearchParams, chooseCode2, chooseCode1, lon,
										lat);
								storeList.addAll(storeList3);
							}
							if (storeList.size() < limit) {
								// 省级没有店铺，查询哈尔滨
								// Region regionId3 = baseMapper.getAdRegionId("230100");//根据adcond查询区域id
								// storeSearchParams.setRegionId(regionId3.getId());
								Region regionId3 = baseMapper.getAdRegionId(chooseCode2);// 根据adcond查询省级区域id
								storeSearchParams.setLimit(limit - storeList.size());
								storeSearchParams.setRegionId(null);
								storeSearchParams.setProvinceId(regionId3.getId());
								List<StoreVO> storeList4 = this.baseMapper.getGoodShop(storeSearchParams.queryWrapper(),
										lon, lat);
								storeList.addAll(storeList4);
							}
						}
					}
				}
			} else {
				// 没有区域，默认显示哈尔滨
				storeList = this.baseMapper.getGoodShop(storeSearchParams.queryWrapper(), lon, lat);
			}

		}
		return storeList;
	}

	public List<StoreVO> getGoodShop(StoreSearchParams storeSearchParams, String adcode, String firstAdcode, String lon,
			String lat) {
		Region regionId = baseMapper.getAdRegionId(adcode);// 根据adcond查询区域id
		if (regionId == null) {
			return new ArrayList<>();
		}
		storeSearchParams.setRegionId(regionId.getId());
		if (ObjectUtil.isNotEmpty(firstAdcode)) {
			Region firstRegion = baseMapper.getAdRegionId(firstAdcode);// 根据adcond查询区域id
			storeSearchParams.setProvinceId(firstRegion.getId());
		}
		List<StoreVO> storeList = this.baseMapper.getGoodShop(storeSearchParams.queryWrapper(), lon, lat);
		return storeList;
	}

	@Override
	public IPage<GoodsVO> getByhotGoods(GoodsSearchParams goodsSearchParams, PageVO page) {
		// 1热销商品
		IPage<GoodsVO> goodsVOList = null;
		QueryWrapper queryWrapper = new QueryWrapper();
		queryWrapper.eq("goods.market_enable", goodsSearchParams.getMarketEnable());
		queryWrapper.eq("goods.delete_flag", false);
		queryWrapper.eq("store.store_disable", "OPEN");
		queryWrapper.eq("goods.auth_flag", "PASS");
		queryWrapper.eq("goods.recommend", true);
		queryWrapper.orderByDesc("goods.recommend_ranking");
		goodsVOList = this.baseMapper.getByhotGoods(PageUtil.initPage(page), queryWrapper);
		if (goodsVOList.getRecords().size() > 0) {
			List<GoodsVO> records = goodsVOList.getRecords();
			for (GoodsVO record : records) {
				String goodsId = record.getId();
				List<GoodsSkuVO> goodsListByGoods = goodsSkuService.getGoodsListByGoodsId(goodsId);
				record.setSkuList(goodsListByGoods);
			}
		}
		if (goodsVOList.getRecords().size() < 10) {
			QueryWrapper wrapper = new QueryWrapper();
			// wrapper.eq("goods.self_operated",goodsSearchParams.getSelfOperated());
			wrapper.eq("goods.market_enable", goodsSearchParams.getMarketEnable());
			wrapper.eq("goods.delete_flag", false);
			wrapper.eq("store.store_disable", "OPEN");
			wrapper.eq("goods.auth_flag", "PASS");
			wrapper.ne("goods.recommend", true);
			wrapper.orderByDesc("monthSales");
			page.setPageSize(10 - goodsVOList.getRecords().size());
			IPage<GoodsVO> goodsVOList1 = this.baseMapper.getByhotGoods(PageUtil.initPage(page), wrapper);
			if (goodsVOList1.getRecords().size() > 0) {
				List<GoodsVO> records = goodsVOList1.getRecords();
				for (GoodsVO record : records) {
					String goodsId = record.getId();
					List<GoodsSkuVO> goodsListByGoods = goodsSkuService.getGoodsListByGoodsId(goodsId);
					record.setSkuList(goodsListByGoods);
				}
			}
			if (goodsVOList.getRecords().size() == 0) {
				goodsVOList.setRecords(goodsVOList1.getRecords());
			} else {
				goodsVOList.getRecords().addAll(goodsVOList1.getRecords());
			}
			goodsVOList.setSize(goodsVOList.getSize() + goodsVOList1.getSize());
			goodsVOList.setTotal(goodsVOList.getTotal() + goodsVOList1.getTotal());
		}
		return goodsVOList;
	}

	public QueryWrapper getWrapper(Boolean selfOperated, String marketEnabl) {
		QueryWrapper queryWrapper = new QueryWrapper();
		queryWrapper.eq("goods.self_operated", selfOperated);
		queryWrapper.eq("goods.market_enable", marketEnabl);
		queryWrapper.eq("goods.delete_flag", false);
		queryWrapper.eq("store.store_disable", "OPEN");
		queryWrapper.orderByDesc("goods.sort");
		return queryWrapper;
	}

	public IPage<GoodsAndStores> getByNewGoodsAndStore(GoodsAndStores goodsAndStores, PageVO page) {
		IPage<GoodsAndStores> goodsAndStoresList = new Page<GoodsAndStores>();
		if (StringUtils.isNotEmpty(goodsAndStores.getTrapeze())) {
			page.setPageSize(page.getPageSize() / 2);
			IPage<GoodsAndStores> byNewGoods = this.baseMapper.getByNewGoods(PageUtil.initPage(page),
					goodsAndStores.goodsWrapper());
			List<GoodsAndStores> records = byNewGoods.getRecords();
			for (GoodsAndStores record : records) {
				String goodsId = record.getGoodsId();
				List<GoodsSkuVO> goodsListByGoods = goodsSkuService.getGoodsListByGoodsId(goodsId);
				record.setSkuList(goodsListByGoods);
			}

			String trapeze = goodsAndStores.getTrapeze();
			String[] split = trapeze.split(",");
			String lon = split[0];
			String lat = split[1];
			IPage<GoodsAndStores> byNewStores = this.baseMapper.byNewStores(PageUtil.initPage(page), lon, lat,
					goodsAndStores.storeWrapper());
			goodsAndStoresList.setRecords(new ArrayList<>());
			for (int i = 0; i < byNewGoods.getRecords().size(); i++) {
				goodsAndStoresList.getRecords().add(byNewGoods.getRecords().get(i));
				for (int j = 0; j < byNewStores.getRecords().size(); j++) {
					goodsAndStoresList.getRecords().add(byNewStores.getRecords().get(i));
					break;
				}
			}
			goodsAndStoresList.setSize(byNewGoods.getSize() + byNewStores.getSize());
			goodsAndStoresList.setTotal(byNewGoods.getTotal() + byNewStores.getTotal());
		} else {
			goodsAndStoresList.setRecords(new ArrayList<>());
		}
		return goodsAndStoresList;
	}

	public IPage<StoreVO> getGoodShopPage(StoreSearchParams storeSearchParams, PageVO page) {
		storeSearchParams.setStoreDisable("OPEN"); // 店铺必须是开启的店铺
		storeSearchParams.setSelfOperated(0); // 查询自营（本地商圈店铺）
		// 1本地商圈2好店推荐;本地商圈需要查詢區域，好店推荐不需要查询区域
		IPage<StoreVO> storeList = new Page<>();
		if (StringUtils.isNotEmpty(storeSearchParams.getChooseCode())) {
			if (null != storeSearchParams.getState() && storeSearchParams.getState() == 1) {
				if (storeSearchParams.getChooseCode() != null || !storeSearchParams.getChooseCode().equals("000000")) {
					String getChooseCode = storeSearchParams.getChooseCode();
					String getChooseCode2 = getChooseCode.substring(0, getChooseCode.length() - 4) + "0000";
					Region regionId2 = baseMapper.getAdRegionId(getChooseCode2);// 根据adcond查询区域id
					storeSearchParams.setRegionId(regionId2.getId());
					String trapeze = storeSearchParams.getTrapeze();
					String lon = "";
					String lat = "";
					if (StringUtils.isNotEmpty(trapeze)) {
						String[] split = trapeze.split(",");
						lon = split[0];
						lat = split[1];
					}
					storeSearchParams.setRecommend(null);
					// storeSearchParams.setSelfOperated(null);
					if (storeSearchParams.getType() != null) {
						if (storeSearchParams.getType().equals("1")) {
							storeSearchParams.setMonthSales(1);
						} else if (storeSearchParams.getType().equals("2")) {
							storeSearchParams.setScore(1.0);
						} else {
							storeSearchParams.setDistance1(1);
						}
					} else {
						storeSearchParams.setDistance1(1);
					}
					storeList = this.baseMapper.getGoodShopPage(PageUtil.initPage(page), lon, lat,
							storeSearchParams.queryWrapper());
					if (storeList.getRecords().size() < 10 || storeList.getTotal() < 10) {
						storeSearchParams.setRegionId(null);
						storeList = this.baseMapper.getGoodShopPage(PageUtil.initPage(page), lon, lat,
								storeSearchParams.queryWrapper());
					}
				} else {
					storeList = this.baseMapper.getStoreList(PageUtil.initPage(page), storeSearchParams.queryWrapper(),
							null, null);
				}
			} else {
				storeList = this.baseMapper.getStoreList(PageUtil.initPage(page), storeSearchParams.queryWrapper(),
						null, null);
			}
		}
		return storeList;
	}

	public IPage<GoodsVO> getGoodPage(GoodsSearchParams goodsSearchParams, PageVO page) {
		IPage<GoodsVO> goodsVOIPage = new Page<>();;
		if (StringUtils.isNotEmpty(goodsSearchParams.getChooseCode())) {
			if (goodsSearchParams.getType() != null) {
				if (goodsSearchParams.getType().equals("1")) {
					goodsSearchParams.setMonthSales(1);
				} else if (goodsSearchParams.getType().equals("2")) {
					goodsSearchParams.setScore(1.0);
				} else {
					goodsSearchParams.setSort("1");
				}
			} else {
				goodsSearchParams.setSort("1");
			}
			// if (ObjectUtil.isNotEmpty(null) ||
			// !goodsSearchParams.getChooseCode().equals("000000")) {
			// String adCode = goodsSearchParams.getChooseCode();
			// String adCode1 = adCode.substring(0, adCode.length() - 2) + "00";
			// Region region = baseMapper.getAdRegionId(adCode1);// 根据adcond查询区域id
			// goodsVOIPage =
			// baseMapper.getGoodPage(PageUtil.initPage(page), region.getId(),
			// goodsSearchParams.getGoodsName(),
			// goodsSearchParams.getMonthSales(), goodsSearchParams.getScore(),
			// goodsSearchParams.getSort());
			// } else {
			goodsVOIPage = baseMapper.getGoodPage(PageUtil.initPage(page), null, goodsSearchParams.getGoodsName(),
					goodsSearchParams.getMonthSales(), goodsSearchParams.getScore(), goodsSearchParams.getSort());
			// }
			List<GoodsVO> records = goodsVOIPage.getRecords();
			for (GoodsVO record : records) {
				String goodsId = record.getId();
				List<GoodsSkuVO> goodsListByGoods = goodsSkuService.getGoodsListByGoodsId(goodsId);
				record.setSkuList(goodsListByGoods);
			}

		}
		return goodsVOIPage;
	}

	@Override
	public IPage<GoodsVO> getByNewGoods(GoodsSearchParams goodsSearchParams, PageVO page) {
		QueryWrapper goodsWrapper = new QueryWrapper();
		goodsWrapper.orderByDesc("goods.create_time");
		goodsWrapper.eq("goods.delete_flag", false);
		goodsWrapper.eq("goods.auth_flag", "PASS");
		goodsWrapper.eq("store.store_disable", StoreStatusEnum.OPEN.name());
		goodsWrapper.eq("goods.market_enable", goodsSearchParams.getMarketEnable());
		IPage<GoodsVO> goods = this.baseMapper.getNewGoods(PageUtil.initPage(page), goodsWrapper);
		return goods;
	}

	@Override
	public Region getAdRegionId(String adCode) {
		return this.baseMapper.getAdRegionId(adCode);
	}

	@Override
	public IPage<CommissionDistributionSale> GetCommissionDistributionSale(QueryWrapper queryWrapper, PageVO page) {
		return this.baseMapper.GetCommissionDistributionSale(PageUtil.initPage(page), queryWrapper);
	}

	@Override
	public IPage<CommissionDistributionSale> GetCommissionDistribution(QueryWrapper queryWrapper, PageVO page) {
		return this.baseMapper.GetCommissionDistribution(PageUtil.initPage(page), queryWrapper);
	}

	@Override
	public IPage<CommissionDistributionSale> GetCommissionDistributionMember(QueryWrapper queryWrapper, PageVO page) {
		return this.baseMapper.GetCommissionDistributionMember(PageUtil.initPage(page), queryWrapper);
	}

}